package io.github.elkan1788.mpservice.module;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.nutz.dao.Sqls;
import org.nutz.dao.impl.NutDao;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

/**
 *
 * @author 凡梦星尘(elkan1788@gmail.com)
 */
@Api("database")
@At("/database")
@IocBean(create="init", depose="depose")
public class MySQLModule {

    @Inject
    private NutDao dao;

    private static final Log logger = Logs.get();

    public void init() {

    }

    public void depose() {

    }

    @POST
    @ApiOperation(value = "查询表数据", notes = "MySQL数据库表的信息", httpMethod = "POST",
            consumes = "application/x-www-form-urlencoded", response = String.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sql", value = "查询语句", defaultValue = "SELECT 1", required = true,
                    paramType = "form", dataType = "string")
    })
    @At
    @Ok("raw")
    public String query(@Param("sql") String sql) {
        String result = "Not data!!!";
        try {
            Sql sqlStmt = Sqls.create(sql);
            sqlStmt.setCallback(new SqlCallback() {
                public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                    List<String> list = new LinkedList<>();
                    while (rs.next())
                        list.add(rs.getString(1));
                    return list;
                }
            });
            this.dao.execute(sqlStmt);
            result = Json.toJson(sqlStmt.getList(String.class));
        } catch (Exception e) {
            logger.error("Query mysql data failed!!!", e);
        }
        return result;
    }
}
